﻿#region Header
// ------------------------ Licence / Copyright ------------------------
// 
// ScrumTable for Scrum Meeting Support
// Copyright © HSR - Hochschule für Technik Rapperswil
// All Rights Reserved
// 
// Author:
//  Michael Gfeller Silvan Gehrig Patrick Boos
// 
// ---------------------------------------------------------------------
#endregion

#region Usings

using System;
using ScrumTable.Common;
using ScrumTable.Common.Data.Tracking;
using ScrumTable.Common.EventHandling;
using ScrumTable.DL.Data.Generic.Properties;

#endregion

namespace ScrumTable.DL.Data.Generic.Cache
{
    /// <summary>
    /// Represents a tracked dictionary value entry.
    /// </summary>
    internal class CacheTrackedDictionaryBucket : ICacheTrackedDictionaryBucket
    {
        #region Declarations
        //--------------------------------------------------------------------
        // Declarations
        //--------------------------------------------------------------------

        private readonly FastSmartWeakEvent<EventHandler> _valueChangedEvents = new FastSmartWeakEvent<EventHandler>();
        private readonly FastSmartWeakEvent<EventHandler> _valueChangingEvents = new FastSmartWeakEvent<EventHandler>();
        private object _value;
        private bool _hasValue;

        #endregion

        #region Properties
        //--------------------------------------------------------------------
        // Properties
        //--------------------------------------------------------------------

        /// <summary>
        /// Gets the name of the underlying element.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets the current bucket value.
        /// </summary>
        public object Value
        {
            get { return _value; }
            set
            {
                bool valuesAreEqual = Equals(_value, value);

                if (!valuesAreEqual || RevManager.IsInitial)
                {
                    if (!valuesAreEqual) { OnValueChanging(EventArgs.Empty); }

                    _value = value;
                    RevManager.Next();

                    if (!valuesAreEqual) { OnValueChanged(EventArgs.Empty); }
                }
                _hasValue = true;
            }
        }

        /// <summary>
        /// Returns true if the current bucket contains a value. This means
        /// that the value has been set once at least.
        /// </summary>
        public bool HasValue
        {
            get { return _hasValue; }
        }

        /// <summary>
        /// Returns true if the current element has changes. This property
        /// is independent from the elements children.
        /// </summary>
        public bool CurrentIsDirty
        {
            get { return !Equals(Value, OriginalValue); }
        }

        /// <summary>
        /// Returns true, if the current bucket is dirty.
        /// </summary>
        public bool IsDirty
        {
            get { return CurrentIsDirty; }
        }

        /// <summary>
        /// Gets the original bucket value.
        /// </summary>
        public object OriginalValue { get; set; }

        /// <summary>
        /// Gets the last valid value stored on the server side. This field is
        /// required for settings because it's needed to check whether the
        /// settings contains an actual (not a user changed) value.
        /// </summary>
        public object LastBackEndValue { get; set; }

        /// <summary>
        /// Gets the internal cache revision of the Value property.
        /// </summary>
        public double CacheRevision
        {
            get { return RevManager.Current; }
        }

        private RevisionManager RevManager { get; set; }

        #endregion

        #region Constructors / Destructor
        //--------------------------------------------------------------------
        // Constructors / Destructor
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new CacheTrackedDictionaryBucket instance.
        /// </summary>
        internal CacheTrackedDictionaryBucket()
        {
            RevManager = new RevisionManager();
        }

        #endregion

        #region Methods
        //--------------------------------------------------------------------
        // Methods
        //--------------------------------------------------------------------

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        object ICloneable.Clone()
        {
            return Clone();
        }

        /// <summary>
        /// Merges the current element with the given cache bucket.
        /// </summary>
        /// <param name="toMerge">Specifies the bucket to merge and import.</param>
        /// <param name="saveProgressFeedback">Specifies the save feedback from the underlying system.</param>
        public void MergeChanges(ICacheTrackedElement toMerge, ICacheSaveProgressFeedback saveProgressFeedback)
        {
            PreCondition.AssertNotNull(toMerge, "toMerge");
            PreCondition.AssertNotNull(saveProgressFeedback, "saveProgressFeedback");
            PreCondition.AssertTrue(typeof(ICacheTrackedDictionaryBucket).IsAssignableFrom(toMerge.GetType()), Resources.ExcCacheElemBaseInvalidImportType);

            switch (saveProgressFeedback.State)
            {
                case CacheSavePairState.Saved:
                    OnMergeChangeSaved((ICacheTrackedDictionaryBucket)toMerge, saveProgressFeedback);
                    break;
                case CacheSavePairState.Deleted:
                    OnMergeChangeDeleted((ICacheTrackedDictionaryBucket)toMerge, saveProgressFeedback);
                    break;
                case CacheSavePairState.Updated:
                    OnMergeChangeInvalidateData((ICacheTrackedDictionaryBucket)toMerge, saveProgressFeedback);
                    break;
                case CacheSavePairState.Error:
                    OnMergeChangeError((ICacheTrackedDictionaryBucket)toMerge, saveProgressFeedback);
                    break;
                default: throw new ArgumentOutOfRangeException();
            }
        }

        /// <summary>
        /// Removes the dirty flag on the current element.
        /// </summary>
        public void RemoveDirtyFlag()
        {
            OriginalValue = Value;
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        /// A new object that is a copy of this instance.
        /// </returns>
        public ICacheTrackedDictionaryBucket Clone()
        {
            return new CacheTrackedDictionaryBucket
            {
                Name = Name,
                Value = CloneValue(Value),
                OriginalValue = CloneValue(OriginalValue),
                LastBackEndValue = LastBackEndValue,
                RevManager = RevManager.Clone()
            };
        }

        private object CloneValue(object toClone)
        {
            if (toClone is ICloneable)
            {
                return ((ICloneable) toClone).Clone();
            }
            return toClone;
        }

        private void ImportFailedChanges(ICacheTrackedDictionaryBucket toMerge)
        {
            if (!IsDirty)
            {
                Value = CloneValue(toMerge.Value);
                Name = toMerge.Name;
                OriginalValue = CloneValue(toMerge.OriginalValue);
                LastBackEndValue = toMerge.LastBackEndValue;
            }
        }

        private void ImportSavedChanges(ICacheTrackedDictionaryBucket toMerge)
        {
            if (!IsDirty)
            {
                ForceImportChanges(toMerge);
            }
        }

        private void ForceImportChanges(ICacheTrackedDictionaryBucket toMerge)
        {
            Value = CloneValue(toMerge.Value);
            Name = toMerge.Name;
            OriginalValue = CloneValue(toMerge.Value);
            LastBackEndValue = toMerge.LastBackEndValue;
        }

        #endregion

        #region Events
        //--------------------------------------------------------------------
        // Events
        //--------------------------------------------------------------------

        /// <summary>
        /// Fires an event which signals after the value property changes.
        /// </summary>
        public event EventHandler ValueChanged
        {
            add { _valueChangedEvents.Add(value); }
            remove { _valueChangedEvents.Remove(value); }
        }

        /// <summary>
        /// Fires an event which signals before the value property changes.
        /// </summary>
        public event EventHandler ValueChanging
        {
            add { _valueChangingEvents.Add(value); }
            remove { _valueChangingEvents.Remove(value); }
        }

        /// <summary>
        /// Fires the ValueChanging event.
        /// </summary>
        /// <param name="e">Specifies the event arguments to send to the clients.</param>
        protected virtual void OnValueChanging(EventArgs e)
        {
            _valueChangingEvents.Raise(this, e);
        }

        /// <summary>
        /// Fires the ValueChanged event.
        /// </summary>
        /// <param name="e">Specifies the event arguments to send to the clients.</param>
        protected virtual void OnValueChanged(EventArgs e)
        {
            _valueChangedEvents.Raise(this, e);
        }

        /// <summary>
        /// An error occurred while saving the given cache element. This means, that
        /// the given element must be merged back (if there are no changes) into
        /// the cache tree.
        /// </summary>
        /// <param name="toMerge">Specifies the cache element which caused the error.</param>
        /// <param name="saveProgressFeedback">Specifies the save feedback provided by the data driver.</param>
        protected virtual void OnMergeChangeError(ICacheTrackedDictionaryBucket toMerge, ICacheSaveProgressFeedback saveProgressFeedback)
        {
            ImportFailedChanges(toMerge);
        }

        /// <summary>
        /// An element on server side has changed (which behaviour may caused an error). Its
        /// cache data must be invalidated in order to resynchronize with the server.
        /// </summary>
        /// <param name="toMerge">Specifies the cache element which data should be invalidated.</param>
        /// <param name="saveProgressFeedback">Specifies the save feedback provided by the data driver.</param>
        protected virtual void OnMergeChangeInvalidateData(ICacheTrackedDictionaryBucket toMerge, ICacheSaveProgressFeedback saveProgressFeedback)
        {
            ForceImportChanges(toMerge);
        }

        /// <summary>
        /// An element has saved on server side. This means that data in the local storage may
        /// be invalidated if the change caused additional changes on server side. Workflow
        /// changes may cause additional value changes.
        /// </summary>
        /// <param name="toMerge">Specifies the cache element which data have ben saved.</param>
        /// <param name="saveProgressFeedback">Specifies the save feedback provided by the data driver.</param>
        protected virtual void OnMergeChangeSaved(ICacheTrackedDictionaryBucket toMerge, ICacheSaveProgressFeedback saveProgressFeedback)
        {
            ImportSavedChanges(toMerge);
        }

        /// <summary>
        /// An element on server side has been deleted. The element in the cache must also be 
        /// deleted.
        /// </summary>
        /// <param name="toMerge">Specifies the cache element which has been deleted.</param>
        /// <param name="saveProgressFeedback">Specifies the save feedback provided by the data driver.</param>
        protected virtual void OnMergeChangeDeleted(ICacheTrackedDictionaryBucket toMerge, ICacheSaveProgressFeedback saveProgressFeedback)
        {
        }

        #endregion
    }
}